package xdu.lz.stage5_jucUtils.chapter3_exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created at 2019/10/19 0019 上午 11:03
 */
public class Exchanger2 {
    public static void main(String[] args) {

        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(()->{
            try {
                System.out.println("T1 start");
                String res = exchanger.exchange("the data from T1",2, TimeUnit.SECONDS);
                System.out.println(Thread.currentThread().getName()+" receive the data:"+res);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
                System.out.println("T1 等待超时");
            }
        },"T1").start();

        new Thread(()->{
            try {
                System.out.println("T2 start");
                Thread.sleep(3000);
                //T1已经超时挂掉了，那么T2会一直阻塞.解决办法在各自的Exception中打断 对方即可
                String res = exchanger.exchange("the data from T2");
                System.out.println(Thread.currentThread().getName()+" receive the data:"+res);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();
    }
}
